<template>
  <div class="project-container">
    <!-- 第一行：项目名称 + 下载按钮 -->
    <div class="project-header">
      <h3 class="project-title">项目名称:{{project.projectName}}</h3>
      <div>
        <el-button type="primary" @click="downloadFile" size="small">项目文件下载</el-button>
        <div v-if="project.docUrl" class="file-info">
          <span>文件: <a :href="project.docUrl" target="_blank">{{ project.docUrl.split('/').pop() }}</a></span>
        </div>
      </div>
    </div>

    <!-- 第二行：项目信息 -->
    <div class="project-info">
      <span>项目编码：{{ project.id }}</span>
      <span>探针类型：{{ project.modelType }}</span>
      <span>
        状态：
          <span class="status-text">{{ signatureStatusText }}</span>
      </span>
      <span>创建时间：{{ project.createTime }}</span>
      <span>截止时间：{{ project.dueTime }}</span>
    </div>

    <!-- 第三行：团队成员 -->
    <div class="project-info">
      <h4 class="team-title">团队成员：</h4>
      <div class="team-info" style="display: flex; gap: 16px;">
        <div><span class="graySpan">设计人员</span> <span class="justSpan">{{ getMemberName(project.designerId) || '未分配' }}</span></div>
        <div><span class="graySpan">校对人员</span> <span class="justSpan">{{ getMemberName(project.verifierId) || '未分配' }}</span></div>
        <div><span class="graySpan">审定人员</span> <span class="justSpan">{{ getMemberName(project.approverId) || '未分配' }}</span></div>
      </div>
    </div>
    <div class="team-section">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane name="design">
          <template #label>
            <i class="el-icon-plus"></i>
            <span style="margin-left: 4px;">设计</span>
          </template>
        </el-tab-pane>
        <el-tab-pane name="verify">
          <template #label>
            <i class="el-icon-check"></i>
            <span style="margin-left: 4px;">校对</span>
          </template>
        </el-tab-pane>
        <el-tab-pane name="approve">
          <template #label>
            <i class="el-icon-warning"></i>
            <span style="margin-left: 4px;">审定</span>
          </template>
        </el-tab-pane>
        <el-tab-pane name="log">
          <template #label>
            <i class="el-icon-user"></i>
            <span style="margin-left: 4px;">日志</span>
          </template>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="this.activeTab === 'design'"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="!multipleSelection"
          @click="handleBatchDelete"
          v-hasPermi="['probe:version:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="this.tabDataMap.design.length==0"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="probeAdd"
          v-hasPermi="['probe:version:add']"
        >新建探针</el-button>
      </el-col>
<!--      <el-col :span="3">-->
<!--        <el-upload-->
<!--          class="upload-demo"-->
<!--          action="#"-->
<!--          :http-request="handleFileUpload"-->
<!--          :on-success="handleSuccess"-->
<!--          :on-error="handleError"-->
<!--          :before-upload="beforeUpload"-->
<!--          :show-file-list="false"-->
<!--          :auto-upload="true"-->
<!--        >-->
<!--          <el-button type="primary" icon="el-icon-upload" size="mini">上传DWG文件</el-button>-->
<!--        </el-upload>-->
<!--      </el-col>-->
    </el-row>
    <!--    动态组件区域-->
    <keep-alive>
      <component
        :is="currentComponent"
        :key="activeTab"
        :table-data="activeTabData"
        :projectId="projectId"
        @selection-change="handleSelectionChange"
        @submit-nextStage="handleSubmitNext"
        @reject-lastStage="handleRejectNext"
        @view-draw="viewDrawing"
        @view-comments="viewComments"
        @edit-design="modifyDesign"
        @update-version="modifyVersion"
      />
    </keep-alive>
    <pagination
      v-show="total >= 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      title="查看批注"
      :visible.sync="remarkDialogVisible"
      width="30%"
    >
      <p>{{ content.remark }}</p>
      <span slot="footer" class="dialog-footer">

        <el-button @click="viewDrawComment">查看批注图纸</el-button>
        <el-button @click="remarkDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <!-- 弹窗 -->
    <el-dialog
      title="文件上传"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <!-- 版本更改文件上传组件 -->
      <el-upload
        action=''
        :http-request="customUpload"
        :before-upload="beforeDocUpload"
        :on-success="handleDocSuccess"
        :on-error="handleDocError"
        :show-file-list="true"
        name="file"
      >
      <el-button type="primary">上传文件</el-button>
      </el-upload>
      <!-- 弹窗底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="probeAddNewVersion">去设计</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {listProbeInfo,getProbeInfo,addProbeInfo,updateProbeInfo,delProbeInfo,getDesignSignature,getVerifySignature,getApproveSignature,getProbeLog } from '@/api/system/probeInfo';
import {listProbeSignatureProcess,getProbeSignatureProcess,addProbeSignatureProcess,updateProbeSignatureProcess,delProbeSignatureProcess} from '@/api/system/probeSignatureProcess';
import {getProbeProject, uploadFile} from '@/api/system/probeProject';
import {getUser, listUser,getUserProfile} from '@/api/system/user';
import {submitProbeSignatureToVerify,rejectProbeSignatureVerify,submitProbeSignatureToApprove,submitProbeSignatureToApprovePass,submitProbeSignatureToApproveReject} from '@/api/system/probeSignatureProcess';
import moment from "moment";
import request from '@/utils/request'
import {addProbeChangeRequest} from "@/api/system/probeChangeRequest";
export default {
  components: {
  },
  data() {
    return {
      total: 0, // 总条目数
      queryParams: {
        pageNum: 1, // 当前页码
        pageSize: 10 // 每页条数
      },
      activeTab: 'design',
      logUserId: null,
      componentMap: { // 组件映射表
        design: () => import('./component/designComponent.vue'),
        verify: () => import('./component/verifyComponent.vue'),
        approve: () => import('./component/approveComponent.vue'),
        log: () => import('./component/logComponent.vue')
      },
      tabDataMap: { // 数据源映射
        design: [],   // 设计 tab 数据
        verify: [],   // 校对 tab 数据
        approve: [],  // 审定 tab 数据
        log: []       // 日志 tab 数据
      },
      names:{},// 设计、校对、审定人员姓名
      projectId: null,
      project:{},
      projectData: {
        id: 1,
        createdBy: '张XX',
        createdTime: '2021-09-09',
        updatedBy: '王XX',
        updatedTime: '2021-09-09',
        name: '探针1.0',
        docUrl: '',
        dueTime: '2021-09-20',
        status: 0,
        modelType: '总温总压探针',
        designerId: 1,
        verifierId: 2,
        approverId: 3
      },
      probeList:[],// 探针列表
      signatureList:[],// 探针签名流程列表
      remarkDialogVisible: false, // 控制弹窗显示
      content: '', // 存储 row 内容，包括remark和annotation
      dialogVisible: false, // 控制版本更改文件上传弹窗显示状态
      dialogRow: null, //
      multipleSelection: null, // 选中行
      userInfo:[],
      memberList: [],
    };
  },
  async created() {
    // 如果传递了record参数才赋值
    if (this.$route.query.id) {
      this.projectId = this.$route.query.id;
    }
    getUserProfile().then(response => {
      console.log('当前登录用户信息', response);
      this.logUserId = response.data.userId;
    });
    await this.getlistUser(); // 获取用户信息
    await this.getProbeProject(); // 根据项目id获取项目详情
    await this.getProbeList(); // 根据项目id获取探针列表
  },
  computed: {
    // 动态计算当前组件
    currentComponent() {
      return this.componentMap[this.activeTab];
    },
    // 动态获取当前 tab 的数据
    activeTabData() {
      console.log('当前tab数据', this.tabDataMap[this.activeTab]);
      return this.tabDataMap[this.activeTab];
    },
    signatureStatusText() {
      const statusMap = {
        0: '创建',
        1: '设计中',
        2: '校对中',
        3: '审定中',
        4: '已发布'
      };
      return statusMap[this.project.status] || '未知状态';
    }
  },
  methods: {
    // 获取用户信息
    async getlistUser() {
      try {
        const response = await listUser();
        this.userInfo = response.rows;
      } catch (error) {
        console.error('获取设计人员信息失败:', error);
      }
    },
    // 根据 ID 查名字
    getMemberName(id) {
      if (!id) return '';
      // 从memberList数组中根据据id找名字
      const member = this.userInfo.find(member => member.userId === id);
      console.log('根据id查找名字',id, member);
      return member ? member.nickName : '';
    },
    async getList() {
      console.log('页面变动',this.queryParams);
      try {
        let response;
        if (this.activeTab === 'design') {
          response = await getDesignSignature(this.projectId, this.queryParams);
        } else if (this.activeTab === 'verify') {
          response = await getVerifySignature(this.projectId, this.queryParams);
        } else if (this.activeTab === 'approve') {
          response = await getApproveSignature(this.projectId, this.queryParams);
        } else if (this.activeTab === 'log') {
          response = await getProbeLog(this.projectId, this.queryParams);
        }
        if (response && response.rows) {
          this.tabDataMap[this.activeTab] = response.rows;
          this.total = response.total;
          console.log('分页数据加载成功:', response);
        }
      } catch (err) {
        console.error('分页数据加载失败:', err);
      }
    },
    // 根据projectId去获取项目详情
    async getProbeProject() {
      try {
        const response = await getProbeProject(this.projectId);
        this.project = response.data;
        console.log('获取项目详情成功:', response);
      } catch (error) {
        console.error('获取项目详情失败:', error);
      }
    },
    async getProbeList() {
      try {
        // 1.获取设计部分签核流程
        const response = await getDesignSignature(this.projectId,this.queryParams);
        this.tabDataMap.design = response.rows;
        this.total = response.total;
        // // 2.获取校对部分签核流程
        // const verifyResponse = await getVerifySignature(this.projectId);
        // this.tabDataMap.verify = verifyResponse.rows;
        // // 3.获取审定部分签核流程
        // const approveResponse = await getApproveSignature(this.projectId);
        // this.tabDataMap.approve = approveResponse.rows;
      } catch (error) {
        console.error('获取探针列表失败:', error);
      }
    },
    // 跳转新建探针界面
    probeAdd() {
      // 路由跳转，并将当前项目id传过去
      this.$router.push({
        name: 'ProbeAdd' ,
        query: {
          projectId: this.project.projectId,
          designerId: this.project.designerId,
          action: 'create'
        }
      });
    },
    probeAddNewVersion() {
      this.$router.push({
        name: 'ProbeAdd',
        query: {
          id: this.dialogRow.id,
          action: 'newVersion'
        }
      })
    },
    parseTime(time, cFormat = 'YYYY-MM-DD HH:mm:ss') {
      if (!time) return '';
      return this.$moment(time).format(cFormat);
    },
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.total = 0;
      const params = JSON.parse(JSON.stringify(this.queryParams));
      if(this.activeTab === 'design') {
        getDesignSignature(this.projectId,params).then(res => {
          this.tabDataMap.design = res.rows;
          console.log('设计tab数据',this.tabDataMap.design);
          this.total = res.total;
        });
      } else if (this.activeTab === 'verify') {
        getVerifySignature(this.projectId,params).then(res => {
          this.tabDataMap.verify = res.rows;
          console.log('校对tab数据',this.tabDataMap.verify);
          this.total = res.total;
        });
      } else if (this.activeTab === 'approve') {
        getApproveSignature(this.projectId,params).then(res => {
          this.tabDataMap.approve = res.rows;
          console.log('审定tab数据',this.tabDataMap.approve);
          this.total = res.total;
        });
      } else if (this.activeTab === 'log') {
        getProbeLog(this.projectId,params).then(res => {
          this.tabDataMap.log = res.rows;
          console.log('日志tab数据',this.tabDataMap.log);
          this.total = res.total;
        });
      }
    },
    // 上传文件之前的处理
    beforeUpload(file) {
      const isDwg = file.name.toLowerCase().endsWith('.dwg');
      if (!isDwg) {
        this.$message.error('只能上传 DWG 文件');
      }
      return isDwg;
    },
    handleFileUpload(uploadOption) {
      const file = uploadOption.file;
      const formData = new FormData();
      formData.append('file', file);

      request({
        url: '/system/save/upload-dwg',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then(response => {
          // 手动触发 on-success
          uploadOption.onSuccess(response, file);
        })
        .catch(error => {
          // 手动触发 on-error
          uploadOption.onError(error);
        });
    },
    handleSuccess(response, file, fileList) {
      this.$message.success('文件上传成功！');
      console.log('文件上传成功:', response);
      const dwgUrl = response.url; // 假设后端返回的是 { url: "..." }
      console.log('DWG文件保存URL:', dwgUrl);
      // 关闭上传文件窗口
    },
    handleError(err, file, fileList) {
      this.$message.error('文件上传失败');
      console.error('文件上传失败:', err);
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    updateProjectData(data) {
      this.projectData = { ...this.projectData, ...data };
    },
    handleDelete(row) {

    },
    downloadFile() {
      // 下载文件逻辑
      const url = this.project.docUrl;
      // 检查链接是否存在
      if (!url) {
        this.$message.warning('暂无可下载的文件');
        return;
      }
      const link = document.createElement('a');
      link.href = url;
      link.download = ''; // 可选：指定下载文件名。为空则使用服务器默认文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    modifyDesign(row,action) {
      // 修改设计逻辑
      // 将当前探针信息传递给新建探针页面
      console.log('修改设计', row);
      this.$router.push({
        name: 'ProbeAdd',
        query: {
          id: row.id,
          action
        }
      });
    },
    handleSubmitNext(row,note) {
      console.log('submit-nextStage', row);
      if (!row.probeInfoId) {
        row.probeInfoId = row.id; // 动态添加 probeInfoId 字段并赋值为 id
      }
      row.operatorId = this.logUserId; // 动态添加 operatorId 字段并赋值为 designerId
      if(note === 'submitToVerify') {
          //提交校对
        console.log('submitToVerify', row);
        submitProbeSignatureToVerify(row).then(res => {
          if (res.code === 200) {
            this.$message.success('提交校对成功');
          } else {
            this.$message.error('提交校对失败');
          }
        }).catch(err => {
          console.error('提交校对失败:', err);
          this.$message.error('提交校对失败');
        });
      } else if(note === 'submitToApprove') {
        // 提交审定
        console.log('submitToApprove', row);
        submitProbeSignatureToApprove(row).then(res => {
          if (res.code === 200) {
            this.$message.success('提交审定成功');
          } else {
            this.$message.error('提交审定失败');
          }
        }).catch(err => {
          console.error('提交审定失败:', err);
          this.$message.error('提交审定失败');
        });
      } else if(note === 'submitToApprovePass') {
        // 审定通过
        submitProbeSignatureToApprovePass(row).then(res => {
          if (res.code === 200) {
            this.$message.success('审定通过成功');
          } else {
            this.$message.error('审定通过失败');
          }
        }).catch(err => {
          console.error('审定通过失败:', err);
          this.$message.error('审定通过失败');
        });
      }
      setTimeout(() => {
        this.getList(); // 刷新列表
      }, 1000);
    },
    handleRejectNext(row,note) {
      // 跳转到draw.vue页面
      this.$router.push({
        name: 'Draw',
        query: {
          row,
          note,
          projectId: this.projectId
        }
      });
    },
    viewDrawing(row) {
      // 查看图纸逻辑
      console.log('查看图纸', row);
      this.$router.push({
        name: 'Draw',
        query:{
          row,
          isComment: 'false'
        }
      });
    },
    viewComments(row) {
      // 查看批注逻辑
      console.log('查看建议', row);
      // 弹窗展示row.remark
      this.content = row;
      this.remarkDialogVisible = true;
    },
    viewDrawComment() {
      this.$router.push({
        name: 'Draw',
        query: {
          // rowId: row.id,        // 推荐传 id，而不是整个对象
          row: this.content,
          isComment: 'true'     // 显式传字符串，在目标页处理时比较方便
        }
      });
    },
    modifyVersion(row,action) {
      // 版本更改逻辑
      this.openDialog();
      this.dialogRow = row;
      console.log('this.dialogRow',this.dialogRow,action)
    },
    // 打开弹窗
    openDialog() {
      this.dialogVisible = true;
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.dialogRow = null;
    },
    // 自定义上传方法
    customUpload({file}) {
      const formData = new FormData();
      formData.append('file', file); // 将文件添加到 FormData 中
      console.log('上传的文件:', file);
      console.log('FormData 文件对象:', formData.get('file')); // ✅ 用 get() 显示具体内容
      // 发送 POST 请求
      uploadFile(formData, {
        headers: {
          'Content-Type': 'multipart/form-data', // 设置请求头（可选，浏览器会自动处理）
        },
      })
        .then((response) => {
          if (response.code === 200) {
            // 假设后端返回成功状态码为 200
            this.handleDocSuccess(response);
          } else {
            this.handleDocError(response.msg || '上传失败');
          }
        })
        .catch((error) => {
          this.handleDocError(error.message || '上传失败');
        });
    },
    // 文件上传前的校验
   beforeDocUpload(file) {
     const isDocOrDocx = file.name.toLowerCase().endsWith('.doc') || file.name.toLowerCase().endsWith('.docx'); // 校验文件是否为doc或docx
     if (!isDocOrDocx) {
       this.$message.error('只能上传 DOC 或 DOCX 文件!');
     }
     return isDocOrDocx;
   },
    // 上传成功的回调
    handleDocSuccess(response) {
      this.$message.success('文件上传成功！');
      console.log('上传结果:', response);
      // 处理返回的数据
      const { url, fileName, newFileName, originalFilename } = response;
      console.log('文件 URL:', url);
      console.log('文件名:', fileName);
      console.log('新文件名:', newFileName);
      console.log('原始文件名:', originalFilename);
      // 版本变更需求
      const data = {
        createdBy: this.logUserId,
        createdTime:moment().format('YYYY-MM-DD HH:mm:ss'),
        docUrl: url,
        referenceProbeId: this.dialogRow.id || this.dialogRow.probeInfoId
      }
      addProbeChangeRequest(data).then(res=>{
        if(res.code === 200) {
          console.log('版本需求变更新增成功')
        }else {
          console.log('版本需求变更新增失败')
        }
      })
      // this.closeDialog();
    },
    // 上传失败的回调
    handleDocError(errorMessage) {
      this.$message.error(`文件上传失败: ${errorMessage}`);
    },
    // 关闭弹窗前的回调
    handleClose(done) {
      this.$confirm('确认关闭弹窗吗？')
        .then(() => {
          done(); // 确认关闭
        })
        .catch(() => {
          // 取消关闭
        });
    },
    // 批量删除
    handleBatchDelete() {
      // 批量删除逻辑
      this.$confirm('确认删除选中的探针吗？','提示',{ type: 'warning'})
        .then(() => {
          console.log('确认删除');
          // 调用删除接口
          const ids = this.multipleSelection.map(item => item.id);
          console.log('批量删除的ID:', ids);
          delProbeInfo(ids).then(res => {
            if (res.code === 200) {
              this.$message.success('批量删除成功');
              this.getList(); // 刷新列表
            } else {
              this.$message.error('批量删除失败');
            }
          });
        })
        .catch(() => {
          // 取消删除
        });
    },
  },
};
</script>

<style scoped>
.project-container {
  padding: 10px 20px;
  font-family: 'Microsoft YaHei', sans-serif;
  color: #333;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.project-title {
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}

.project-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 10px;
  font-size: 14px;
}

.status-text {
  color: #409EFF; /* ElementUI主色蓝 */
  cursor: pointer;
}

.team-title {
  font-size: 14px;
  font-weight: bold;
  margin-right: 10px;
}
.team-info{
  border: 1px solid #ccc;
}
.graySpan {
  background-color: #cccccc;
  display: inline-block;
  min-width: 100px;
  text-align: center;
}
.justSpan {
  display: inline-block;
  min-width: 100px;
  text-align: center;
}
.mb8 { margin-bottom: 8px; }
.small-padding .el-table__cell { padding: 6px 8px; }
.fixed-width .el-button { margin: 0 4px; }
</style>
